Write code that enhances all arrays such that you can call the array.groupBy(fn) method on any array and it will return a grouped version of the array.
A grouped array is an object where each key is the output of fn(arr[i]) and each value is an array containing all items in the original array which generate that key.
The provided callback fn will accept an item in the array and return a string key.
The order of each value list should be the order the items appear in the array. Any order of keys is acceptable.
Please solve it without lodash's _.groupBy function.
寫一個可以將數列分組的語法,透過提供的方法進行分組。
解法如下:
Array.prototype.groupBy = function(fn) {
const result = {};
this.forEach(item => {
const key = fn(item);
if (!result.hasOwnProperty(key)){
result[key] = [];
}
result[key].push(item);
});
return result;
};
思路:
設定結果是一個多陣列(const result = {};),因為在範例1中是在陣列中再包含陣列;
用this代表Array,並巡歷;
透過fn(item)的回傳值來分組;
所以我們可以判斷result是否有這個回傳值,有就增加,沒有就創造。
那判斷「指定的屬性」是否存在,就可以使用.hasOwnProperty()方法。